﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using Newtonsoft.Json;
using System.Net.Security;
using System.Text.RegularExpressions;
using System.IO.Compression;
namespace Star.Tools.Http
{
    public class HttpHelper
    {
        #region 预定义方法或者变更
        //默认的编码
        private Encoding encoding = Encoding.Default;
        //Post数据编码
        private Encoding postencoding = Encoding.Default;
        //HttpWebRequest对象用来发起请求
        private HttpWebRequest request = null;
        //获取影响流的数据对象
        private HttpWebResponse response = null;
        /// <summary>
        /// 根据相传入的数据，得到相应页面数据
        /// </summary>
        /// <param name="item">参数类对象</param>
        /// <returns>返回HttpResult类型</returns>
        public HttpResult GetHtml(HttpItem item)
        {
            //返回参数
            HttpResult result = new HttpResult();
            try
            {
                //准备参数
                SetRequest(item);
            }
            catch (Exception ex)
            {
                result = new HttpResult();
                result.Cookie = string.Empty;
                result.Header = null;
                result.Html = ex.Message;
                result.StatusDescription = "配置参数时出错：" + ex.Message;
                return result;
            }
            try
            {
                #region 得到请求的response
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    result.StatusCode = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                    result.Header = response.Headers;
                    if (response.Cookies != null) result.CookieCollection = response.Cookies;
                    if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
                    MemoryStream _stream = new MemoryStream();
                    //GZIIP处理
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                    }
                    else
                    {
                        //开始读取流并设置编码方式
                        //response.GetResponseStream().CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(response.GetResponseStream());
                    }
                    //获取Byte
                    byte[] ResponseByte = _stream.ToArray();
                    _stream.Close();
                    if (ResponseByte != null & ResponseByte.Length > 0)
                    {
                        //是否返回Byte类型数据
                        if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
                        //从这里开始我们要无视编码了
                        if (encoding == null)
                        {
                            Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                            string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToLower() : string.Empty;
                            if (c.Length > 2)
                                encoding = Encoding.GetEncoding(c.Trim().Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk"));
                            else
                            {
                                if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8;
                                else encoding = Encoding.GetEncoding(response.CharacterSet);
                            }
                        }
                        //得到返回的HTML
                        result.Html = encoding.GetString(ResponseByte);
                    }
                    else
                    {
                        //得到返回的HTML
                        result.Html = "本次请求并未返回任何数据";
                    }
                }
                #endregion
            }
            catch (WebException ex)
            {
                //这里是在发生异常时返回的错误信息
                response = (HttpWebResponse)ex.Response;
                result.Html = ex.Message;
                if (response != null)
                {
                    result.StatusCode = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            if (item.IsToLower) result.Html = result.Html.ToLower();
            return result;
        }
        /// <summary>
        /// 4.0以下.net版本取数据使用
        /// </summary>
        /// <param name="streamResponse">流</param>
        private MemoryStream GetMemoryStream(Stream streamResponse)
        {
            MemoryStream _stream = new MemoryStream();
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = streamResponse.Read(buffer, 0, Length);
            while (bytesRead > 0)
            {
                _stream.Write(buffer, 0, bytesRead);
                bytesRead = streamResponse.Read(buffer, 0, Length);
            }
            return _stream;
        }
        /// <summary>
        /// 为请求准备参数
        /// </summary>
        ///<param name="item">参数列表</param>
        private void SetRequest(HttpItem item)
        {
            // 验证证书
            SetCer(item);
            //设置Header参数
            if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
                {
                    request.Headers.Add(key, item.Header[key]);
                }
            // 设置代理
            SetProxy(item);
            if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
            request.ServicePoint.Expect100Continue = item.Expect100Continue;
            //请求方式Get或者Post
            request.Method = item.Method;
            request.Timeout = item.Timeout;
            request.KeepAlive = item.KeepAlive;
            request.ReadWriteTimeout = item.ReadWriteTimeout;
            //Accept
            request.Accept = item.Accept;
            //ContentType返回类型
            request.ContentType = item.ContentType;
            //UserAgent客户端的访问类型，包括浏览器版本和操作系统信息
            request.UserAgent = item.UserAgent;
            // 编码
            encoding = item.Encoding;
            //设置Cookie
            SetCookie(item);
            //来源地址
            request.Referer = item.Referer;
            //是否执行跳转功能
            request.AllowAutoRedirect = item.Allowautoredirect;
            //设置Post数据
            SetPostData(item);
            //设置最大连接
            if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
        }
        /// <summary>
        /// 设置证书
        /// </summary>
        /// <param name="item"></param>
        private void SetCer(HttpItem item)
        {
            if (!string.IsNullOrEmpty(item.CerPath))
            {
                //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //初始化对像，并设置请求的URL地址
                request = (HttpWebRequest)WebRequest.Create(item.URL);
                SetCerList(item);
                //将证书添加到请求里
                request.ClientCertificates.Add(new X509Certificate(item.CerPath));
            }
            else
            {
                //初始化对像，并设置请求的URL地址
                request = (HttpWebRequest)WebRequest.Create(item.URL);
                SetCerList(item);
            }
        }
        /// <summary>
        /// 设置多个证书
        /// </summary>
        /// <param name="item"></param>
        private void SetCerList(HttpItem item)
        {
            if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
            {
                foreach (X509Certificate c in item.ClentCertificates)
                {
                    request.ClientCertificates.Add(c);
                }
            }
        }
        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="item">Http参数</param>
        private void SetCookie(HttpItem item)
        {
            if (!string.IsNullOrEmpty(item.Cookie))
                //Cookie
                request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
            //设置Cookie
            if (item.CookieCollection != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(item.CookieCollection);
            }
        }
        /// <summary>
        /// 设置Post数据
        /// </summary>
        /// <param name="item">Http参数</param>
        private void SetPostData(HttpItem item)
        {
            //验证在得到结果时是否有传入数据
            if (request.Method.Trim().ToLower().Contains("post"))
            {
                if (item.PostEncoding != null)
                {
                    postencoding = item.PostEncoding;
                }
                byte[] buffer = null;
                //写入Byte类型
                if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
                {
                    //验证在得到结果时是否有传入数据
                    buffer = item.PostdataByte;
                }//写入文件
                else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(item.Postdata))
                {
                    StreamReader r = new StreamReader(item.Postdata, postencoding);
                    buffer = postencoding.GetBytes(r.ReadToEnd());
                    r.Close();
                } //写入字符串
                else if (!string.IsNullOrEmpty(item.Postdata))
                {
                    buffer = postencoding.GetBytes(item.Postdata);
                }
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
            }
        }
        /// <summary>
        /// 设置代理
        /// </summary>
        /// <param name="item">参数对象</param>
        private void SetProxy(HttpItem item)
        {
            if (!string.IsNullOrEmpty(item.ProxyIp))
            {
                //设置代理服务器
                if (item.ProxyIp.Contains(":"))
                {
                    string[] plist = item.ProxyIp.Split(':');
                    WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
                    //建议连接
                    myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
                    //给当前请求对象
                    request.Proxy = myProxy;
                }
                else
                {
                    WebProxy myProxy = new WebProxy(item.ProxyIp, false);
                    //建议连接
                    myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
                    //给当前请求对象
                    request.Proxy = myProxy;
                }
                //设置安全凭证
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
        }
        /// <summary>
        /// 回调验证证书问题
        /// </summary>
        /// <param name="sender">流对象</param>
        /// <param name="certificate">证书</param>
        /// <param name="chain">X509Chain</param>
        /// <param name="errors">SslPolicyErrors</param>
        /// <returns>bool</returns>
        

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        {
            return true;
        }
        #endregion

        #region
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="getParam"></param>
        /// <returns></returns>
        public static Stream GetStream(string url, object getParam)
        {
            return RequestStream(new HttpParam()
            {
                Url = url,
                Method = "GET",
                GetParam = getParam
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postParam"></param>
        /// <returns></returns>
        public static Stream PostStream(string url, object postParam)
        {
            return RequestStream(new HttpParam()
            {
                Url = url,
                Method = "POST",
                GetParam = postParam
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        public static string RequestString(HttpParam param)
        {
            var result = "";
            using (var reader = new StreamReader(RequestStream(param), param.Encoding))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
        public static Stream RequestStream(HttpParam param)
        {
            #region 处理地址栏参数
            var getParamSb = new StringBuilder();
            if (param.GetParam != null)
            {
                if (param.GetParam is string)
                {
                    getParamSb.Append(param.GetParam.ToString());
                }
                else
                {
                    param.GetParam.GetType().GetProperties().ToList().ForEach(d =>
                    {
                        getParamSb.AppendFormat("{0}={1}&", d.Name, d.GetValue(param.GetParam, null));
                    });
                }
            }
            if (!string.IsNullOrWhiteSpace(getParamSb.ToString().TrimEnd('&')))
            {
                param.Url = string.Format("{0}?{1}", param.Url, getParamSb.ToString().TrimEnd('&'));
            }
            #endregion
            var r = WebRequest.Create(param.Url) as HttpWebRequest;
            if (!string.IsNullOrWhiteSpace(param.CertPath) && !string.IsNullOrWhiteSpace(param.CertPwd))
            {
                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                var cer = new X509Certificate2(param.CertPath, param.CertPwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
                r.ClientCertificates.Add(cer);
                #region 暂时不要的
                //ServicePointManager.Expect100Continue = true;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                //req.ProtocolVersion = HttpVersion.Version11;
                //req.UserAgent = SUserAgent;
                //req.KeepAlive = false;
                //var cookieContainer = new CookieContainer();
                //req.CookieContainer = cookieContainer;
                //req.Timeout = 1000 * 60;
                //req.Headers.Add("x-requested-with", "XMLHttpRequest");
                #endregion
            }
            r.Timeout = param.TimeOut * 1000;
            r.UserAgent = param.UserAgent;
            r.Method = param.Method ?? "POST";
            r.Referer = param.Referer;
            r.CookieContainer = param.CookieContainer;
            r.ContentType = param.ContentType;
            if (param.PostParam != null)
            {
                var postParamString = "";
                if (param.PostParam is string)
                {
                    postParamString = param.PostParam.ToString();
                }
                else if (param.ParamType == HttpParamType.Form)
                {
                    var dicParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(param.PostParam));
                    //postParamString = dicParam.Aggregate(postParamString, (current, dic) => current + (dic.Key + "=" + dic.Value + "&")).TrimEnd('&');
                }
                else
                {
                    postParamString = JsonConvert.SerializeObject(param.PostParam);
                }
                var bs = param.Encoding.GetBytes(postParamString);
                r.ContentLength = bs.Length;
                using (var rs = r.GetRequestStream())
                {
                    rs.Write(bs, 0, bs.Length);
                }
            }
            return r.GetResponse().GetResponseStream();
        }
      

        /// <summary>
        /// 文件上传至远程服务器。传入：Url、CookieContainer、PostParam、PostedFile
        /// </summary>
        public static string PostFile(HttpParam param)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(param.Url);
            request.CookieContainer = param.CookieContainer;
            request.Method = "POST";
            request.Timeout = 20000;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.KeepAlive = true;
            var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            var boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
            var buffer = new byte[param.PostedFile.ContentLength];
            param.PostedFile.InputStream.Read(buffer, 0, buffer.Length);
            var strHeader = "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
            strHeader = string.Format(strHeader,
                                     "filedata",
                                     param.PostedFile.FileName,
                                     param.PostedFile.ContentType);
            var byteHeader = ASCIIEncoding.ASCII.GetBytes(strHeader);
            try
            {
                using (var stream = request.GetRequestStream())
                {
                    if (param.PostParam != null)
                    {
                        var postParamString = "";
                        if (param.PostParam is string)
                        {
                            postParamString = param.PostParam.ToString();
                        }
                        else
                        {
                            postParamString = JsonConvert.SerializeObject(param.PostParam);
                        }
                        var bs = param.Encoding.GetBytes(postParamString);
                        stream.Write(bs, 0, bs.Length);
                    }
                    stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    stream.Write(byteHeader, 0, byteHeader.Length);
                    stream.Write(buffer, 0, buffer.Length);
                    var trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    stream.Write(trailer, 0, trailer.Length);
                    stream.Close();
                }
                var response = (HttpWebResponse)request.GetResponse();
                var result = "";
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
                response.Close();
                return result;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        #endregion
    }

    //public class HttpWebHelper
    //{
    //    #region 初始化
    //    public WebProxy Proxy { get; set; }

    //    public CookieCollection Cookies => _cookies;

    //    #endregion

    //    public void ClearCookies()
    //    {
    //        _cookies = new CookieCollection();
    //    }

    //    #region private
    //    private CookieCollection _cookies = new CookieCollection();

    //    private const string DefaultUserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";

    //    /// <summary>  
    //    /// 创建GET方式的HTTP请求  
    //    /// </summary>  
    //    /// <param name="url">请求的URL</param>  
    //    /// <param name="timeout">请求的超时时间</param>  
    //    /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
    //    /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>
    //    /// <param name="referer"></param>
    //    /// <param name="headers"></param>
    //    /// <param name="contentType"></param>
    //    /// <param name="keepAlive"></param>
    //    /// <param name="accept"></param>
    //    /// <returns></returns>  
    //    private HttpWebResponse CreateGetHttpResponse(string url, int? timeout = 300, string userAgent = "", CookieCollection cookies = null
    //        , string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {

    //        if (string.IsNullOrEmpty(url))
    //        {
    //            throw new ArgumentNullException("url");
    //        }

    //        HttpWebRequest request;
    //        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    //        {
    //            ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
    //            request = WebRequest.Create(url) as HttpWebRequest;
    //            request.ProtocolVersion = HttpVersion.Version10;
    //        }
    //        else
    //        {
    //            request = WebRequest.Create(url) as HttpWebRequest;
    //        }

    //        if (Proxy != null)
    //        {
    //            request.Proxy = Proxy;
    //        }

    //        request.Method = "GET";
    //        request.Headers["Pragma"] = "no-cache";
    //        request.Accept = accept;
    //        request.Headers["Accept-Language"] = "en-US,en;q=0.5";

    //        request.ContentType = contentType;

    //        request.UserAgent = DefaultUserAgent;
    //        request.Referer = referer;
    //        if (keepAlive.HasValue)
    //        {
    //            request.KeepAlive = keepAlive.Value;
    //        }
    //        if (headers != null)
    //        {
    //            foreach (var header in headers)
    //            {
    //                request.Headers.Add(header.Key, header.Value);
    //            }
    //        }


    //        if (!string.IsNullOrEmpty(userAgent))
    //        {
    //            request.UserAgent = userAgent;
    //        }
    //        if (timeout.HasValue)
    //        {
    //            request.Timeout = timeout.Value * 1000;
    //        }
    //        if (cookies != null)
    //        {
    //            request.CookieContainer = new CookieContainer();
    //            request.CookieContainer.Add(cookies);
    //        }
    //        else
    //        {
    //            request.CookieContainer = new CookieContainer();
    //            request.CookieContainer.Add(Cookies);
    //        }
    //        var v = request.GetResponse() as HttpWebResponse;

    //        return v;
    //    }

    //    /// <summary>  
    //    /// 创建POST方式的HTTP请求  
    //    /// </summary>  
    //    /// <param name="url">请求的URL</param>  
    //    /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
    //    /// <param name="timeout">请求的超时时间</param>  
    //    /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
    //    /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
    //    /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>
    //    /// <param name="headers"></param>
    //    /// <param name="contentType"></param>
    //    /// <param name="keepAlive"></param>
    //    /// <param name="referer"></param>
    //    /// <param name="accept"></param>
    //    /// <returns></returns>  
    //    private HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        var paramsStr = CreateParameter(parameters);
    //        return CreatePostHttpResponse(url, paramsStr, requestEncoding, timeout, userAgent, cookies, referer, headers, contentType, keepAlive, accept);
    //    }

    //    /// <summary>  
    //    /// 创建POST方式的HTTP请求  
    //    /// </summary>  
    //    /// <param name="url">请求的URL</param>  
    //    /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
    //    /// <param name="timeout">请求的超时时间</param>  
    //    /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
    //    /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
    //    /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>
    //    /// <param name="referer"></param>
    //    /// <param name="headers"></param>
    //    /// <param name="contentType"></param>
    //    /// <param name="keepAlive"></param>
    //    /// <param name="accept"></param>
    //    /// <returns></returns>  
    //    private HttpWebResponse CreatePostHttpResponse(string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {

    //        if (string.IsNullOrEmpty(url))
    //        {
    //            throw new ArgumentNullException("url");
    //        }
    //        if (requestEncoding == null)
    //        {
    //            throw new ArgumentNullException("requestEncoding");
    //        }
    //        HttpWebRequest request;
    //        //如果是发送HTTPS请求  
    //        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    //        {
    //            ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
    //            request = WebRequest.Create(url) as HttpWebRequest;
    //            request.ProtocolVersion = HttpVersion.Version10;
    //        }
    //        else
    //        {
    //            request = WebRequest.Create(url) as HttpWebRequest;
    //        }

    //        if (Proxy != null)
    //        {
    //            request.Proxy = Proxy;
    //        }

    //        request.Method = "POST";
    //        request.Headers.Add("Accept-Language", "zh-CN,en-GB;q=0.5");
    //        request.Accept = accept;
    //        request.Referer = referer;
    //        request.Headers["Accept-Language"] = "en-US,en;q=0.5";
    //        request.UserAgent = DefaultUserAgent;
    //        request.ContentType = contentType;
    //        request.Headers["Pragma"] = "no-cache";
    //        if (keepAlive.HasValue)
    //        {
    //            request.KeepAlive = keepAlive.Value;
    //        }
    //        if (cookies != null)
    //        {
    //            request.CookieContainer = new CookieContainer();
    //            request.CookieContainer.Add(cookies);
    //        }
    //        else
    //        {
    //            request.CookieContainer = new CookieContainer();
    //            request.CookieContainer.Add(Cookies);
    //        }

    //        if (headers != null)
    //        {
    //            foreach (var header in headers)
    //            {
    //                request.Headers.Add(header.Key, header.Value);
    //            }
    //        }


    //        if (!string.IsNullOrEmpty(userAgent))
    //        {
    //            request.UserAgent = userAgent;
    //        }
    //        else
    //        {
    //            request.UserAgent = DefaultUserAgent;
    //        }

    //        if (timeout.HasValue)
    //        {
    //            request.Timeout = timeout.Value * 1000;
    //        }

    //        request.Expect = string.Empty;

    //        //如果需要POST数据  
    //        if (!string.IsNullOrEmpty(parameters))
    //        {
    //            byte[] data = requestEncoding.GetBytes(parameters);
    //            using (Stream stream = request.GetRequestStream())
    //            {
    //                stream.Write(data, 0, data.Length);
    //            }
    //        }

    //        var v = request.GetResponse() as HttpWebResponse;

    //        return v;
    //    }

    //    /// <summary>  
    //    /// 创建POST方式的HTTP请求  
    //    /// </summary>  
    //    /// <param name="url">请求的URL</param>
    //    /// <param name="filePath"></param>
    //    /// <param name="timeout">请求的超时时间</param>  
    //    /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>
    //    /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>
    //    /// <param name="referer"></param>
    //    /// <param name="headers"></param>
    //    /// <param name="contentType"></param>
    //    /// <param name="keepAlive"></param>
    //    /// <param name="accept"></param>
    //    /// <returns></returns>  
    //    private HttpWebResponse CreatePostFileHttpResponse(string url, string filePath, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {

    //        if (string.IsNullOrEmpty(url))
    //        {
    //            throw new ArgumentNullException("url");
    //        }

    //        HttpWebRequest request;
    //        //如果是发送HTTPS请求  
    //        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    //        {
    //            ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
    //            request = WebRequest.Create(url) as HttpWebRequest;
    //            request.ProtocolVersion = HttpVersion.Version10;
    //        }
    //        else
    //        {
    //            request = WebRequest.Create(url) as HttpWebRequest;
    //        }


    //        if (Proxy != null)
    //        {
    //            request.Proxy = Proxy;
    //        }

    //        request.Method = "POST";
    //        request.Accept = accept;
    //        request.Referer = referer;
    //        request.Headers["Accept-Language"] = "en-US,en;q=0.5";
    //        request.UserAgent = DefaultUserAgent;
    //        request.ContentType = contentType;
    //        request.Headers["Pragma"] = "no-cache";
    //        if (keepAlive.HasValue)
    //        {
    //            request.KeepAlive = keepAlive.Value;
    //        }
    //        if (headers != null)
    //        {
    //            foreach (var header in headers)
    //            {
    //                request.Headers.Add(header.Key, header.Value);
    //            }
    //        }

    //        if (cookies != null)
    //        {
    //            request.CookieContainer = new CookieContainer();
    //            request.CookieContainer.Add(cookies);
    //        }
    //        else
    //        {
    //            request.CookieContainer = new CookieContainer();
    //            request.CookieContainer.Add(Cookies);
    //        }


    //        if (!string.IsNullOrEmpty(userAgent))
    //        {
    //            request.UserAgent = userAgent;
    //        }
    //        else
    //        {
    //            request.UserAgent = DefaultUserAgent;
    //        }

    //        if (timeout.HasValue)
    //        {
    //            request.Timeout = timeout.Value * 1000;
    //        }

    //        request.Expect = string.Empty;

    //        //如果需要POST数据  
    //        if (!string.IsNullOrEmpty(filePath))
    //        {
    //            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    //            {
    //                //时间戳 
    //                string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
    //                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");

    //                //请求头部信息 
    //                StringBuilder sb = new StringBuilder();
    //                sb.Append("--");
    //                sb.Append(strBoundary);
    //                sb.Append("\r\n");
    //                sb.Append("Content-Disposition: form-data; name=\"");
    //                sb.Append("file");
    //                sb.Append("\"; filename=\"");
    //                sb.Append(fs.Name);
    //                sb.Append("\"");
    //                sb.Append("\r\n");
    //                sb.Append("Content-Type: ");
    //                sb.Append("application/octet-stream");
    //                sb.Append("\r\n");
    //                sb.Append("\r\n");
    //                string strPostHeader = sb.ToString();
    //                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);


    //                request.ContentType = "multipart/form-data; boundary=" + strBoundary;
    //                long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;

    //                request.ContentLength = length;

    //                //开始上传时间 

    //                byte[] filecontent = new byte[fs.Length];

    //                fs.Read(filecontent, 0, filecontent.Length);

    //                using (Stream stream = request.GetRequestStream())
    //                {

    //                    //发送请求头部消息 
    //                    stream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

    //                    stream.Write(filecontent, 0, filecontent.Length);

    //                    //添加尾部的时间戳 
    //                    stream.Write(boundaryBytes, 0, boundaryBytes.Length);
    //                }

    //            }
    //        }
    //        var v = request.GetResponse() as HttpWebResponse;

    //        return v;
    //    }

    //    private static string CreateParameter(IDictionary<string, string> parameters)
    //    {
    //        var buffer = new StringBuilder();
    //        foreach (string key in parameters.Keys)
    //        {
    //            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
    //        }
    //        return buffer.ToString().TrimStart('&');
    //    }

    //    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    //    {
    //        return true; //总是接受  
    //    }

    //    public string Post(string url, IDictionary<string, string> parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        var response = CreatePostHttpResponse(url, parameters, requestEncoding, timeout, userAgent, cookies, referer, headers, contentType, keepAlive);

    //        try
    //        {
    //            using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding))
    //            {
    //                return reader.ReadToEnd();
    //            }
    //        }
    //        catch (Exception)
    //        {
    //            return null;
    //        }
    //    }
    //    #endregion

    //    #region public
    //    #region Post
    //    public T Post<T>(string url, IDictionary<string, string> parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        return JsonConvert.DeserializeObject<T>(Post(url, parameters, requestEncoding, responseEncoding, timeout, userAgent, cookies, referer, headers, contentType, keepAlive));
    //    }

    //    public string Post(string url, string parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        HttpWebResponse response = CreatePostHttpResponse(url, parameters, requestEncoding, timeout, userAgent, cookies, referer, headers, contentType, keepAlive: keepAlive);

    //        try
    //        {
    //            using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding))
    //            {
    //                return reader.ReadToEnd();
    //            }
    //        }
    //        catch (Exception)
    //        {
    //            return null;
    //        }
    //    }

    //    public T Post<T>(string url, string parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        var result = Post(url, parameters, requestEncoding, responseEncoding, timeout, userAgent, cookies, referer,
    //            headers, contentType, keepAlive);
    //        return result.FromJson<T>();
    //    }

    //    public string PostFile(string url, string filePath, Encoding responseEncoding,
    //        int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "",
    //        Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        HttpWebResponse response = CreatePostFileHttpResponse(url, filePath, timeout, userAgent, cookies, referer,
    //            headers, contentType, keepAlive);

    //        try
    //        {
    //            using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding))
    //            {
    //                return reader.ReadToEnd();
    //            }
    //        }
    //        catch (Exception)
    //        {
    //            return null;
    //        }
    //    }

    //    #endregion

    //    #region Get
    //    public string Get(string url, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null
    //        , string referer = "", Dictionary<string, string> headers = null, string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        var response = CreateGetHttpResponse(url, timeout, userAgent, cookies, referer, headers, contentType, keepAlive);
    //        using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding))
    //        {
    //            return reader.ReadToEnd();
    //        }
    //    }

    //    public T Get<T>(string url, Encoding responseEncoding, int? timeout = 300, string userAgent = "",
    //        CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null,
    //        string contentType = "application/x-www-form-urlencoded", bool? keepAlive = true, string accept = "*/*")
    //    {
    //        var result = Get(url, responseEncoding, timeout, userAgent, cookies, referer, headers, contentType,
    //            keepAlive);
    //        return result.FromJson<T>();
    //    }

    //    public byte[] GetFile(string url, out Dictionary<string, string> header, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, bool? keepAlive = true, string accept = "*/*")
    //    {
    //        HttpWebResponse response = CreateGetHttpResponse(url, timeout, userAgent, cookies, referer, headers, keepAlive: keepAlive);

    //        header = response.Headers.AllKeys.ToDictionary(key => key, key => response.Headers[key]);

    //        try
    //        {
    //            Stream st = response.GetResponseStream();

    //            byte[] by = new byte[response.ContentLength];

    //            st.Read(by, 0, by.Length);

    //            st.Close();

    //            return by;
    //        }
    //        catch (Exception)
    //        {
    //            return null;
    //        }
    //    }

    //    public Stream GetStream(string url, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string referer = "", Dictionary<string, string> headers = null, bool? keepAlive = true, string accept = "*/*")
    //    {
    //        var response = CreateGetHttpResponse(url, timeout, userAgent, cookies, referer, headers, keepAlive: keepAlive);

    //        return response.GetResponseStream();
    //    }
    //    #endregion
    //    #endregion
    //}



   
    

}
